//
//  BKMeViewModel.m
//  baokaodaxue
//
//  Created by dangyangyang on 15/6/9.
//  Copyright (c) 2015年 宏图教育. All rights reserved.
//

#import "BKMeViewModel.h"

@implementation BKMeViewModel

+ (void)avardaWithSuccess:(void (^)(NSString *message))success failure:(void (^)(NSString *))failure{

    NSURL *url = [NSURL URLWithString:@"http://www.baokaodaxue.com/bk/mobile/ioshead"];
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
   
    [request setTimeoutInterval:10.0];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    
    NSDictionary *cookieDic = [userDefault objectForKey:@"Cookie"];
    NSString *cookieString = [NSString stringWithFormat:@"%@=%@",cookieDic[@"name"],cookieDic[@"value"]];
    
    [request setValue:cookieString forHTTPHeaderField:@"Cookie"];
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    
    
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror:%@%ld", error.localizedDescription,(long)error.code);
                               }else{
                                   NSDictionary *responseDic=[NSJSONSerialization JSONObjectWithData:data
                                                                                             options:NSJSONReadingMutableLeaves
                                                                                               error:nil];
                                   
                                   if ([[responseDic objectForKey:@"code"] isEqualToString:@"200"]) {
                                       
                                       success(responseDic[@"extraData"]);
                                       
                                       
                                   }else{
                                       
                                       NSString *messge = [responseDic objectForKey:@"message"];
                                       if ([messge isEqualToString:@"请先登录"]) {
                                           NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                                           [userDefaults removeObjectForKey:@"Cookie"];
                                           
                                       }
                                       failure([responseDic objectForKey:@"message"]);
                                   }
                               }
                           }];
    

}

@end
